<template>
  <div class="create-or-edit">
    <el-form>
      <el-form-item label="资源名称">
        <el-input v-model="resource.name"></el-input>
      </el-form-item>
      <el-form-item  label="资源路径">
        <el-input v-model="resource.url"></el-input>
      </el-form-item>
      <el-form-item label="资源分类">
         <el-select v-model="resource.categoryId" placeholder="资源分类" clearable>
           <!-- 请求接口进行下拉菜单项设置 -->
           <!-- 进行数据遍历操作 -->
           <el-option
           v-for="item in resourcecategories"
           :key="item.index"
           :label="item.name"
           :value="item.id">
           </el-option>
           <!-- <el-option label="区域二" value="beijing"></el-option> -->
         </el-select>
      </el-form-item>
      <el-form-item label="描述">
        <el-input v-model="resource.description" type="textarea"></el-input>
      </el-form-item>
      <el-button @click="onCancel">取 消</el-button>
      <el-button type="primary" @click="onSubmit">确 定</el-button>
    </el-form>
  </div>
</template>

<script>
import { saveOrUpdateResource, getResourceById } from '@/services/resource'
export default {
  name: 'CreateOrEdit',
  props: {
    resourcecategories: {
      type: Array,
      default: () => { return [] }
    },
    isEdit: {
      type: Boolean,
      // 默认为添加功能
      default: false
    },
    resourceId: {
      type: [Number, String],
      required: true
    }
  },
  created () {
    //  加载上级角色信息
    this.loadResourceById()
  },
  data () {
    return {
      resource: {
        name: '',
        categoryId: '',
        url: '',
        description: ''
      }
    }
  },
  methods: {
    // 点击取消按钮
    onCancel () {
    // 向父组件传递取消的状态
      this.$emit('fail')
      // 关闭提示框(需要子组件向父组件传递取消的状态)并清除表单
      this.$message.error('已取消')
      this.resource = {}
    },
    async onSubmit () {
      const { data } = await saveOrUpdateResource(this.resource)
      // console.log(data)
      // console.log(this.resourcecategories)
      if (data.code === '000000') {
        // 关闭提示框(需要子组件向父组件传递资源添加成功的状态)并清除表单
        this.$emit('success')
        this.$message.success('资源添加成功!')
        // 清除表单的数据
        this.resource = {}
      }
    },
    async loadResourceById () {
      console.log(this.resourceId)
      // const id = this.resourceId || undefined
      if (this.resourceId) {
        const { data } = await getResourceById(this.resourceId)
        console.log(data)
        if (data.code === '000000') {
        // 将上级菜单数据保存，并绑定给视图解构
          this.resource = data.data
        }
      }
    }
  }
}
</script>
<style lang="scss" scoped></style>
